package com.yhao.service;

import com.yhao.Dao.LoginRepository;
import com.yhao.bean.login.LoginBean;
import com.yhao.bean.login.LoginResult;
import com.yhao.utils.TokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.concurrent.TimeUnit;

@Service
public class LoginService {
    @Autowired
    private LoginRepository loginDao;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    //token有效期为7天
    public LoginResult login(String userName, String password) {
        LoginResult loginResult = new LoginResult();
        if (StringUtils.isEmpty(userName) || StringUtils.isEmpty(password)) {
            loginResult.setCode(20);
            loginResult.setMassage("用户名或密码不能为空");
        } else {
            LoginBean loginBean = loginDao.findByUserName(userName);
            if (loginBean != null && password.equals(loginBean.getPassword())) {
                loginResult.setCode(1);
                String token = TokenUtil.getToken(userName, new Date().getTime());
                loginResult.setToken(token);
                redisTemplate.opsForValue().set(userName, token, 7, TimeUnit.DAYS);
                loginResult.setMassage("登录成功");
            } else {
                loginResult.setCode(21);
                loginResult.setMassage("帐号或密码输入错误");
            }
        }
        return loginResult;
    }

}
